import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form, Popconfirm, message } from 'antd';
import React, { useRef, useState } from 'react';
import { pageModule, batchDelModule, addModule, updateModule } from './service';
import { history, useModel } from '@umijs/max';
import { getProjectList } from '@/components/RightContent/service';

// @ts-ignore
const handleRemove = async (idList: any[]) => {
  const hide = message.loading('正在删除');
  if (!idList) return true;

  try {
    const res = await batchDelModule({
      idList
    });
    hide();
    if (res.code === 0) {
      message.success('删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [editForm] = Form.useForm()
  const [addForm] = Form.useForm()
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const { initialState } = useModel('@@initialState');

  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      valueType: 'indexBorder'
    },
    {
      title: '模块名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [{ required: true }]
      },
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              history.push('/stress-test/case?moduleId=' + entity.id)
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '所属项目',
      dataIndex: 'projectId',
      valueType: 'select',
      hideInForm: true,
      hideInSearch: true,
      async request() {
        const res = await getProjectList({})

        return res?.data?.map((item: any) => ({
          ...item,
          label: item.name,
          value: item.id
        })) || []
      }
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <BetaSchemaForm<any>
          form={editForm}
          key="edit"
          trigger={<a
            onClick={() => {
              editForm.setFieldsValue(record)
            }}
          >
            编辑
          </a>}
          layoutType="ModalForm"
          modalProps={{
            width: 350,
            title: '编辑模块'
          }}
          onFinish={async (values) => {
            const hide = message.loading('正在保存');
            try {
              const res = await updateModule({
                id: record?.id,
                ...values,
                projectId: initialState?.currentProject?.id
              })
              hide();
              if (res?.code == 0) {
                message.success('保存成功，即将刷新');
                actionRef.current?.reload()
                return true;
              } else {
                message.error('保存失败，请重试');
                return false;
              }
            } catch (error) {
              hide();
              message.error('保存失败，请重试');
              return false;
            }
          }}
          columns={columns as any}
        />,
        <Popconfirm key='del' title="是否要删除此行？" onConfirm={async () => {
          const res = await handleRemove([record?.id])
          if (res) {
            actionRef.current?.reload()
          }
          return res
        }}>
          <a onClick={() => {
          }}>删除</a>
        </Popconfirm>

      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any>
        actionRef={actionRef}
        rowKey="id"
        search={{
        }}
        toolBarRender={() => [
          <BetaSchemaForm<any>
            key="addModule"
            form={addForm}
            trigger={<Button
              type='primary'
              onClick={() => {
                addForm?.resetFields()
              }}
            >
              新建模块
            </Button>}
            layoutType="ModalForm"
            modalProps={{
              width: 350,
              title: '新建模块'
            }}
            onFinish={async (values) => {
              const hide = message.loading('正在保存');
              try {
                const res = await addModule({
                  ...values,
                  projectId: initialState?.currentProject?.id
                })
                hide();
                if (res?.code == 0) {
                  message.success('保存成功，即将刷新');
                  actionRef.current?.reload()
                  return true;
                }
              } catch (error) {
                hide();
                message.error('保存失败，请重试');
                return false;
              }
            }}
            columns={columns as any}
          />
        ]}
        request={async ({ pageSize, current, ...params }) => {
          const res = await pageModule({
            current,
            pageSize,
            ...params,
            projectId: initialState?.currentProject?.id,
          })
          const total = res?.data?.totalRecords || 0
          const data = res?.data?.currentData || []
          return {
            data,
            total,
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Popconfirm key='del' title={`是否要批量删除 ${selectedRowsState.length} 条？`} onConfirm={async () => {
            const res = await handleRemove(selectedRowsState.map((row: any) => row.id));
            if (res) {
              actionRef.current?.reloadAndRest?.()
              setSelectedRows([]);
            }
          }}>
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
